package com.un.ebs.product.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.un.ebs.core.exception.BusinessDataRepeatException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.product.domain.Product;
import com.un.ebs.product.domain.ProductSkuExt;
import com.un.ebs.product.dto.ProductDto;
import com.un.ebs.product.enums.ProductChargeTypeEnum;
import com.un.ebs.product.enums.ProductPurchaseTypeEnum;
import com.un.ebs.product.enums.ProductUnitTypeEnum;
import com.un.ebs.product.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * @author liubo
 * @email liubocs@163.com
 * @date 2020/5/16 23:15
 */
public class BomDetailListener extends AnalysisEventListener<BomDetailDto> {

    private static final Logger logger = LoggerFactory.getLogger(BomDetailListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 10;

    private final List<BomDetailDto> list = new ArrayList<>();

    private final ProductService productService;

    private final String targetClassId;

    public BomDetailListener(ProductService service, String targetClassId) {
        this.productService = service;
        this.targetClassId = targetClassId;

        if (this.productService == null) {
            throw new BusinessException("服务不能为空。");
        }
        if (StringUtils.isNullOrEmpty(targetClassId)) {
            throw new BusinessException("导入时未指定品类。");
        }
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * @param context
     */
    @Override
    public void invoke(BomDetailDto data, AnalysisContext context) {
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        logger.warn("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {

        logger.warn("{}条数据，开始存储数据库！", list.size());
        if (StringUtils.isNullOrEmpty(this.targetClassId)) {
            return;
        }

        for (BomDetailDto obj : list) {
            if (StringUtils.isNullOrEmpty(obj.getCode()) || StringUtils.isNullOrEmpty(obj.getName())) {
                throw new BusinessException("物料编号或物料名称不能为空。");
                //continue;
            }

            Product product = productService.queryByCode(obj.getCode());
            String spuId;
            if (product == null) {
                ProductDto spu = new ProductDto();
                spu.setName(obj.getName());
                spu.setCode(obj.getCode());
                if ("外部采购".equals(obj.getStockType()) || "F".equals(obj.getStockType())) {
                    spu.setPurchaseType(ProductPurchaseTypeEnum.Purchase);
                } else if ("自制生产".equals(obj.getStockType()) || "内部生产".equals(obj.getStockType()) || "E".equals(obj.getStockType())) {
                    spu.setPurchaseType(ProductPurchaseTypeEnum.Produce);
                } else if ("客户供料".equals(obj.getStockType()) || "客供料".equals(obj.getStockType())) {
                    spu.setPurchaseType(ProductPurchaseTypeEnum.CustomerProvider);
                } else {
                    spu.setPurchaseType(ProductPurchaseTypeEnum.Default);
                }
                spu.setUnitType(ProductUnitTypeEnum.ProductQty);
                spu.setChargeType(ProductChargeTypeEnum.BeforePay);
                spu.setPrice(0d);
                spu.setClassId(targetClassId);
                spuId = productService.add(spu, false);
            } else {
                spuId = product.getId();
                product.setName(obj.getName());
                product.setClassId(targetClassId);
                if ("外部采购".equals(obj.getStockType()) || "F".equals(obj.getStockType())) {
                    product.setPurchaseType(ProductPurchaseTypeEnum.Purchase);
                } else if ("自制生产".equals(obj.getStockType()) || "内部生产".equals(obj.getStockType()) || "E".equals(obj.getStockType())) {
                    product.setPurchaseType(ProductPurchaseTypeEnum.Produce);
                } else if ("客户供料".equals(obj.getStockType()) || "客供料".equals(obj.getStockType())) {
                    product.setPurchaseType(ProductPurchaseTypeEnum.CustomerProvider);
                } else {
                    product.setPurchaseType(ProductPurchaseTypeEnum.Default);
                }
                product.updateById();
            }

            try {
                if (!StringUtils.isNullOrEmpty(obj.getMainSkuCode())) {
                    bomInit(obj, spuId);
                }
            } catch (BusinessDataRepeatException ex) {
                logger.error("保存错误：" + ex.getMessage());
                ex.printStackTrace();
            } catch (Exception ex) {
                logger.error("保存错误 ： " + obj.getCode());
                ex.printStackTrace();
            }
            //System.out.println(obj);
        }
        logger.warn("存储数据库成功！");
        //System.out.println();
    }

    private void bomInit(BomDetailDto obj, String spuId) {
        if (StringUtils.isNullOrEmpty(obj.getMainSkuCode())) {
            return;
        }

        try {
            Product spu = productService.queryByCode(obj.getMainSkuCode());
            if (spu == null) {
                logger.error("指定的主产品编码不存在。");
                return;
            }

            for(ProductSkuExt sku :  productService.querySkuById(spuId)){
                productService.addInclude(spu.getId(), sku.getId(), obj.getUserQty());
            }

        } catch (Exception e) {
            System.out.println("bom item init error : " + JSON.toJSONString(obj));
            e.printStackTrace();
        }
    }
}
